package com.haixiaoke.saas.enterprise.user.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.RepeatSubmit;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.constant.TenantConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysUser;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.department.domain.Tenant;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.domain.LoginBody;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import com.haixiaoke.saas.system.framework.web.service.SysLoginService;
import com.haixiaoke.saas.system.framework.web.service.SysPermissionService;
import com.haixiaoke.saas.system.framework.web.service.TokenService;
import com.haixiaoke.saas.user.domain.BizTenantUser;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @Author panda
 * @Date 2023/12/20
 **/
@RestController
@RequestMapping("/enterprise/user/userBusiness")
public class EnterpriseBizUserBusinessController extends BaseController {


    @Autowired
    private IBizUserBusinessService bizUserBusinessService;
    @Autowired
    private ITenantService iTenantService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ITenantService tenantService;
    @Autowired
    private SysPermissionService permissionService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:user:list')")
    @GetMapping("/list")
    @TenantScope
    public TableDataInfo list(BizUserBusiness user) {
        startPage();
        user.setTenantId(TenantContext.getTenantId());
        List<BizUserBusiness> list = bizUserBusinessService.selectUserBusListByDep(user);
        return getDataTable(list);
    }


    /**
     * 获取机构下所有用户信息
     *
     * @param user
     * @return
     */
    @GetMapping("/userList")
    @TenantScope
    public AjaxResult userList(BizUserBusiness user) {
        user.setTenantId(TenantContext.getTenantId());
        List<BizUserBusiness> list = bizUserBusinessService.selectUserBusListByDep(user);
        return success(list);
    }


    /**
     * 检测用户状态和查询机构集合
     *
     * @param user
     * @return
     */
    @PostMapping("/selectUserDep")
    public AjaxResult selectUserDep(@RequestBody BizUserBusiness user) {
        sysLoginService.validateCaptcha(user.getPhonenumber(), user.getCode(), user.getUuid(), false);
        BizUserBusiness userBusiness = bizUserBusinessService.selectBizUserByPhonenumber(user.getPhonenumber());
        AjaxResult ajax;
        if (ObjectUtil.isEmpty(userBusiness)) {
            ajax = AjaxResult.error("该账号不存在");
        } else {
            if (SecurityUtils.matchesPassword(user.getPassword(), userBusiness.getPassword())) {
                List<Tenant> tenantList = iTenantService.selectDepByUserId(userBusiness.getUserId());
                if (tenantList.isEmpty()) {
                    ajax = AjaxResult.error("该账号没有所属机构");
                } else {
                    ajax = AjaxResult.success();
                    ajax.put("depList", tenantList);
                }
            } else {
                ajax = AjaxResult.error("账号密码错误");
            }

        }
        return ajax;
    }


    /**
     * 根据手机号码查询用户状态和查询机构集合
     *
     * @param user
     * @return
     */
    @PostMapping("/selectMobileUserDep")
    public AjaxResult selectMobileUserDep(@RequestBody BizUserBusiness user) {
        BizUserBusiness userBusiness = bizUserBusinessService.selectBizUserByPhonenumber(user.getPhonenumber());
        AjaxResult ajax;
        if (ObjectUtil.isEmpty(userBusiness)) {
            ajax = AjaxResult.error("该账号不存在");
        } else {
            List<Tenant> tenantList = iTenantService.selectDepByUserId(userBusiness.getUserId());
            if (tenantList.isEmpty()) {
                ajax = AjaxResult.error("该账号没有所属机构");
            } else {
                ajax = AjaxResult.success();
                ajax.put("depList", tenantList);
            }

        }
        return ajax;
    }

    /**
     * 检测用户状态和查询机构集合
     *
     * @return
     */
    @GetMapping("/checkUserState")
    public AjaxResult checkUserState() {
//        BizUserBusiness userBusiness = bizUserBusinessService.selectBizUserBusinessByphonenumber(user.getPhonenumber());
        BizUserBusiness userBusiness = bizUserBusinessService.selectBizUserBusinessByUserId(getUserId(), getLoginUser().getTenantId());
        AjaxResult ajax;
        if (ObjectUtil.isEmpty(userBusiness)) {
            ajax = AjaxResult.error("该账号不存在");
        } else {
            ajax = AjaxResult.success();
            if (BizUserBusiness.ACTIVATE_STATUS_NOT_ACTIVATED.equals(userBusiness.getActivateStatus())) {
                ajax.put("state", true);
            } else if (BizUserBusiness.ACTIVATE_STATUS_ACTIVATED.equals(userBusiness.getActivateStatus())) {
                ajax.put("state", false);
            }
        }
        return ajax;
    }

    /**
     * 查询用户的机构集合
     *
     * @param userId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:user:query')")
    @GetMapping("/getDepListByUserId/{userId}")
    public AjaxResult getDepListByUserId(@PathVariable("userId") Long userId) {
        return success(iTenantService.selectDepByUserId(userId));
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping("/{userId}")
    @TenantScope
    public AjaxResult changeStatus(@PathVariable("userId") Long userId) {
        return success(bizUserBusinessService.selectBizUserBusinessByUserId(userId, TenantContext.getTenantId()));
    }

    @PreAuthorize("@ss.hasPermi('enterprise:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    @TenantScope
    public AjaxResult enterpriseAdd(@Validated @RequestBody BizUserBusiness user) {
        if (StrUtil.isBlank(TenantContext.getTenantId())) {
            return error("缺少机构标识");
        }
        user.setTenantId(TenantContext.getTenantId());
        if (!bizUserBusinessService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !bizUserBusinessService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNull(user.getRoleId())) {
            return error("角色数据异常");
        }
        if (StringUtils.isNull(user.getDeptId())) {
            return error("部门数据异常");
        }
        if (iTenantService.checkPopulation(user.getTenantId())) {
            return error("该企业已达到最大人数");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        return success(bizUserBusinessService.insertBizUserBusiness(user));
    }

    @PreAuthorize("@ss.hasPermi('enterprise:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    @TenantScope
    public AjaxResult enterpriseEdit(@Validated @RequestBody BizUserBusiness user) {
        if (StrUtil.isBlank(TenantContext.getTenantId())) {
            return error("缺少机构标识");
        }
        user.setTenantId(TenantContext.getTenantId());
        user.setOldTenantId(TenantContext.getTenantId());
        if (!bizUserBusinessService.checkUserNameUnique(user)) {
            return error("编辑用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !bizUserBusinessService.checkPhoneUnique(user)) {
            return error("编辑用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNull(user.getRoleId())) {
            return error("角色数据异常");
        }
        if (StringUtils.isNull(user.getDeptId())) {
            return error("部门数据异常");
        }
        user.setUpdateBy(getUsername());
        user.setPassword(null);
        return success(bizUserBusinessService.updateBizUserBusiness(user));
    }

    /**
     * 用户修改密码
     *
     * @param user
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:user:edit')")
    @PutMapping("/editPassword")
    public AjaxResult editPassword(@RequestBody BizUserBusiness user) {
        user.setUpdateBy(getUsername());
        return success(bizUserBusinessService.updateBizUserPassword(user));
    }

    /**
     * 用户首次登录时修改密码
     *
     * @param user
     * @return
     */
    @PutMapping("/login/editPassword")
    public AjaxResult loginEditPassword(@RequestBody BizUserBusiness user) {
        BizUserBusiness userBusiness = bizUserBusinessService.selectBizUserBusinessByUserId(getUserId(), getLoginUser().getTenantId());
        if (ObjectUtil.isNotEmpty(userBusiness)) {
            if (BizUserBusiness.ACTIVATE_STATUS_ACTIVATED.equals(userBusiness.getActivateStatus())) {
                return error("该账号已激活！");
            }
            user.setUserId(userBusiness.getUserId());
            int i = bizUserBusinessService.updateBizUserPassword(user);
            if (i > 0) {
                if (BizUserBusiness.ACTIVATE_STATUS_NOT_ACTIVATED.equals(userBusiness.getActivateStatus())) {
                    BizUserBusiness newUser = new BizUserBusiness();
                    newUser.setUserId(userBusiness.getUserId());
                    newUser.setActivateStatus(BizUserBusiness.ACTIVATE_STATUS_ACTIVATED);
                    bizUserBusinessService.updateUserBusState(newUser);
                }
            }
            return toAjax(i);
        }
        return error("账号不存在");
    }


    /**
     * 忘记密码
     *
     * @param user
     * @return
     */
    @PutMapping("/forget/editPassword")
    public AjaxResult forgetEditPassword(@RequestBody BizUserBusiness user) {
        sysLoginService.validateMobileCaptcha(user.getPhonenumber(), user.getCode(), true);
        BizUserBusiness userBusiness = bizUserBusinessService.selectBizUserByPhonenumber(user.getPhonenumber());
        if (ObjectUtil.isNotEmpty(userBusiness)) {
            user.setUserId(userBusiness.getUserId());
            int i = bizUserBusinessService.updateBizUserPassword(user);
            return toAjax(i);
        }
        return error("账号不存在");
    }


    /**
     * 删除用户下某个机构与用户的关联数据
     *
     * @param userId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userId}")
    @TenantScope
    public AjaxResult remove(@PathVariable("userId") Long userId) {
        BizTenantUser depUser = new BizTenantUser();
        depUser.setUserId(userId);
        depUser.setTenantId(TenantContext.getTenantId());
        return toAjax(bizUserBusinessService.deleteBizUserBusinessByUserId(depUser));
    }

    @GetMapping("/checkUser/{phonenumber}")
    public AjaxResult checkUser(@PathVariable String phonenumber) {
        return bizUserBusinessService.checkUser(phonenumber);
    }


    /**
     * 修改用户信息
     */
    @PutMapping("editUser")
    @RepeatSubmit
    public AjaxResult editUser(@RequestBody BizUserBusiness user) {
        LoginUser loginUser = getLoginUser();
        BizUserBusiness bizUser = loginUser.getBizUser();
        user.setUserName(bizUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !bizUserBusinessService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !bizUserBusinessService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(bizUser.getUserId());
        user.setPassword(null);
        if (bizUserBusinessService.updateBizUser(user) > 0) {
            // 更新缓存用户信息
            bizUser.setNickName(user.getNickName());
            bizUser.setPhonenumber(user.getPhonenumber());
            bizUser.setEmail(user.getEmail());
            bizUser.setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 切换企业
     */
    @PutMapping("/switchingEnterprise")
    @RepeatSubmit
    public AjaxResult switchingEnterprise(@RequestBody LoginBody loginBody) {
        LoginUser loginUser = getLoginUser();
        Tenant tenant = tenantService.selectDepartmentByDepId(loginBody.getTenantId());
        if (TenantConstants.TENANT_STATUS_NO.equals(tenant.getTenantStatus())) {
            return AjaxResult.error("该机构已被禁用");
        }
        BizUserBusiness bizUser = bizUserBusinessService.selectBizUserBusinessByphonenumber(loginUser.getBizUser().getPhonenumber(), loginBody.getTenantId());
        if (ObjectUtil.isEmpty(bizUser)) {
            return AjaxResult.error("该账号不存在");
        }
        bizUser.setTenantId(loginBody.getTenantId());
        Set<String> menuPermission = permissionService.getMenuPermission(bizUser, loginBody.getTenantId());
        loginUser.setBizUser(bizUser);
        loginUser.setTenantId(loginBody.getTenantId());
        loginUser.setPermissions(menuPermission);
        tokenService.setLoginUser(loginUser);
        return success();
    }
}
